package com.zxw.java基础.socket.BIO;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @projectName: util-cloud
 * @package: com.zxw.java基础.scolet
 * @className: Server
 * @author: zhangxuewei
 * @description: BIO通信服务端
 * @date: 2023/11/4 15:50
 * @version: 1.0
 */
public class Server {

    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        // 绑定端口
        serverSocket.bind(new InetSocketAddress(10002));
        System.out.println("server start...");
        while (true) {
            // serverSocket.accept() 会阻塞 **************
            executorService.execute(new ServerTask(serverSocket.accept()));
        }

    }

    private static class ServerTask implements Runnable {

        private Socket socket = null;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @SneakyThrows
        @Override
        public void run() {
            // 拿客户端和服务端交流的数据管道
            try (
                    ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream())
            ) {
                // 拿客户端的输出
                String username = input.readUTF();
                System.out.println("client send text:" + username + ",Thread-name:" + Thread.currentThread());

                output.writeUTF("hello " + username + ", nice to meet you,how old are you?");
                output.flush();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                socket.close();
            }
        }
    }
}
